package com.fe.class02;

import java.util.Arrays;

/**
 * @Description 异或运算来实现两数交换
 * @Author sosuke :-)
 * @Date 2021/12/2 22:14
 */
public class Code01_Swap {

    public static void main(String[] args) {
        /**
         * 异或运算可以看做无进位相加
         * 1. 0 ^ N = N
         * 2. N ^ N = 0
         * 3. 异或运算满足交换律和结合律
         */
        int a = 6;
        int b = 16;
        System.out.println("a = " + a + ", b = " + b);
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
        System.out.println("a = " + a + ", b = " + b);

        int[] arr = {3,8,2};
        int i = 0;
        int j = 1;
        System.out.println(Arrays.toString(arr));
        swap(arr, i, j);
        System.out.println(Arrays.toString(arr));
    }

    // i 和 j 是同一位置的话会出错，值会刷为0
    public static void swap (int[] arr, int i, int j) {
        arr[i]  = arr[i] ^ arr[j];
        arr[j]  = arr[i] ^ arr[j];
        arr[i]  = arr[i] ^ arr[j];
    }


}
